package com.yywq.controller;

import com.alibaba.druid.util.StringUtils;
import com.yywq.error.BusinessException;
import com.yywq.error.EnumBusinessError;
import com.yywq.mapper.UserMapper;
import com.yywq.pojo.User;
import com.yywq.pojo.model.UserToken;
import com.yywq.pojo.view.UserView;
import com.yywq.response.CommonReturnType;
import com.yywq.service.impl.UserServiceImpl;
import com.yywq.utils.FTPUtil;
import com.yywq.utils.MyUtil;
import com.yywq.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

/**
 * @author: 吴磊
 * @program: yywq
 * @create: 2021-03-21 00:19
 */
@RestController
@RequestMapping("/user")
//跨域问题
//@CrossOrigin(allowCredentials = "true", origins = "*")
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private MyUtil myUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FTPUtil ftpUtil;

    @Autowired
    private TokenUtils tokenUtils;


    /**
     * @param telPhone
     * @param password
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    private CommonReturnType login(@RequestParam("telPhone") String telPhone,
                                   @RequestParam("password") String password) throws Exception {
        //入参校验
        if (StringUtils.isEmpty(telPhone) || StringUtils.isEmpty(password)) {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR);
        }
        //用户登录服务，用来校验用户登录是否合法
        User loginUser = userService.login(telPhone, password);
        //生成当前用户专有Token
        UserToken userToken = new UserToken();
        BeanUtils.copyProperties(loginUser, userToken);
        String token = tokenUtils.generateToken(userToken);

        //然后存到redis，并设置时间为1天
        myUtil.Token(token, telPhone);
        UserToken info = tokenUtils.getInfoFromToken(token);
        HashMap<Object, Object> map = new HashMap();
        map.put("token", token);
        map.put("login_user", info);
        return CommonReturnType.create(map);
    }


    /**
     * 用户注册接口
     *
     * @param nickName
     * @param realName
     * @param sex
     * @param birthday
     * @param telPhone
     * @param password
     * @param verification
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    private CommonReturnType register(@RequestParam("nickName") String nickName,
                                      @RequestParam("realName") String realName,
                                      @RequestParam("sex") String sex,
                                      @RequestParam("birthday") String birthday,
                                      @RequestParam("telPhone") String telPhone,
                                      @RequestParam("password") String password,
                                      @RequestParam("verification") String verification,
                                      MultipartFile file) throws BusinessException {
        if (myUtil.verificationIsOk(telPhone, verification)) {
            User user = new User();

            user.setId(MyUtil.getUUID());
            user.setNickName(nickName);
            user.setRealName(realName);
            user.setSex(sex);
            user.setBirthday(birthday);
            user.setTelPhone(telPhone);
            user.setPassword(password);

            try {
                int i = userService.register(user);
                if (i > 0) {
                    //如果上面都没问题，就上传图片
                    String pic_url = ftpUtil.uploadFolder(file);
                    userMapper.updateUserPicture(telPhone, pic_url);
                }

            } catch (Exception e) {
                throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "注册失败，数据库插入失败");
            }
        } else {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR, "验证码错误");
        }
        return CommonReturnType.create(null);
    }

    /**
     * 用于判断注册的时候手机号是否已经被注册
     *
     * @param telPhone
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/phoneIsOk", method = RequestMethod.POST)
    private CommonReturnType telPhoneIsOk(@RequestParam("telPhone") String telPhone) throws BusinessException {
        System.out.println(telPhone);
        User user = userMapper.getUserByTelPhone(telPhone);
        if (user != null) {
            throw new BusinessException(EnumBusinessError.USER_IS_EXIST);
        }
        return CommonReturnType.create(null);
    }


    /**
     * 登录成功后获取用户名称
     *
     * @param telPhone
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/getUserName", method = RequestMethod.POST)
    private CommonReturnType loginOkReturnUserName(@RequestParam("telPhone") String telPhone) throws BusinessException {
        if (StringUtils.isEmpty(telPhone)) {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR);
        }
        User user = userMapper.getUserByTelPhone(telPhone);
        return CommonReturnType.create(user.getNickName());
    }

    /**
     * 用户退出登录、关闭浏览器的时候移除token
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    private CommonReturnType loginOut(@RequestParam("token") String token) throws BusinessException {
        myUtil.removeToken(token);
        return CommonReturnType.create(null);
    }


    /**
     * 获取用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    private CommonReturnType getUserInfo(@RequestParam("id") String id) {
        UserView userView = userService.getUserView(id);
        return CommonReturnType.create(userView);
    }
}
